<?php

namespace app\api\controller;

use app\common\controller\Api;
use App\Models\Good;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Request;

/**
 * 首页
 */
class GoodsWelfare extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /*
     * 福利商品详情
     */
    public function goods_welfare()
    {
        $id = $this->request->param('id');
        $goods_welfare = Db::name("goods_welfare")->where('id', $id)->where('welfare_status', 0)->find();
        if (!$goods_welfare) {
            $this->error('该福利商品已失效', '', 303);
        }
        $goods = Db::name("goods")
            ->where("id = {$goods_welfare['goods_id']}")
            ->where("status = 1")
            ->where("is_del = 0")
            ->field("id as goods_id,name,price,sale_num,image,images,introduce,chandi,brand,parameter,zhongliang,expressfee_id,status,spec1,spec2,content,integral,province,city")
            ->find();
        if (!$goods) {
            $this->error('该福利商品已失效', '', 303);
        }
        $goodsStock = Db::name("goods_stock t1")
            ->join('goods_spec_one t2', 't1.goods_spec_one_id = t2.id')
            ->join('goods_spec_two t3', 't1.goods_spec_two_id = t3.id', "LEFT")
            ->where('t1.id',$goods_welfare['goods_stock_id'])
            ->field('t2.name as goods_spec_one_name,t3.name as goods_spec_two_name,t1.image as goods_stock_image')
            ->find();
        if (!$goodsStock) {
            $this->error('该福利商品已失效', '', 303);
        }
        $goods['image'] = path($goods['image']);
        $images = explode(',', $goods['images']);
        $image = array();
        foreach ($images as $kk => $vv) {
            $image[] = path($vv);
        }
        $goods['images'] = $image;
        $goods['goods_spec_one_name'] = $goodsStock['goods_spec_one_name'];
        $goods['goods_spec_two_name'] = $goodsStock['goods_spec_two_name'];
        $goods['goods_stock_image'] = path($goodsStock['goods_stock_image']);
        $goods['welfare_id'] = $goods_welfare['id'];
        $goods['welfare_status'] = $goods_welfare['welfare_status'];
        $goods['welfare_price'] = $goods_welfare['welfare_price'];
        $this->success('成功', $goods, 200);
    }

    /*
     * 福利商品下单
     */
    public function goods_welfare_order()
    {
        $request = Request::instance();
        $userId = $request->param("userhome_id");
        $data = [
            'welfare_id' => $request->param("welfare_id"),//商品福利id
            'address_id' => $request->param("address_id"),//地址id
            'paytype' => $request->param("paytype"),//地址id
        ];
        $res = yanzheng($userId, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $EmptyData = array('welfare_id', 'address_id', 'paytype');
        foreach ($EmptyData as $oeVo) {
            $retInfo = EmptyValidate($oeVo, $data);
            if ($retInfo) {
                $this->error($retInfo, '', 201);
            }
        }

        try {
            Db::startTrans();
            $goods_welfare = Db::name("goods_welfare")->where('id', $data['welfare_id'])->where('welfare_status', 0)->lock(true)->find();
            if (!$goods_welfare) {
                $this->error('该福利商品已失效', '', 303);
            }
            $goods = Db::name("goods")
                ->where("id = {$goods_welfare['goods_id']}")
                ->where("status = 1")
                ->where("is_del = 0")
                ->field("*")
                ->find();
            if (!$goods) {
                $this->error('该福利商品已失效', '', 303);
            }
            $cutOffTime = strtotime("2022-11-02 23:59:59");
            if($goods['createtime'] <= $cutOffTime){
                $this->error('因疫情原因,当地区已不支持发货', '', 391);
            }
            $goodsStock = Db::name("goods_stock t1")
                ->join('goods_spec_one t2', 't1.goods_spec_one_id = t2.id')
                ->join('goods_spec_two t3', 't1.goods_spec_two_id = t3.id', "LEFT")
                ->where('t1.id',$goods_welfare['goods_stock_id'])
                ->field('t2.id as goods_spec_one_id,t3.id as goods_spec_two_id,t2.name as goods_spec_one_name,t3.name as goods_spec_two_name,t1.image as goods_stock_image,t1.zhongliang
                    ,t1.cost_price,t1.pure_cost_price,t1.price,t1.vip_price,t1.use_integral')
                ->find();
            if (!$goodsStock) {
                $this->error('该福利商品已失效', '', 303);
            }
            $data['goods_spec_one_id'] = $goodsStock['goods_spec_one_id'];
            $data['goods_spec_two_id'] = $goodsStock['goods_spec_two_id'];
            $data['num'] = 1;
            $newOrder = New NewOrder();
            $res = $newOrder->setWelfare($data, $userId,$goods_welfare,$goods,$goodsStock);
            $num = Db::name("goods_welfare")->where('goods_id', $goods_welfare['goods_id'])->where('welfare_status', 0)->count();
            if ($num) {
                Db::name("goods")->where('id', $goods_welfare['goods_id'])->update(['is_welfare' => 1]);
            } else {
                Db::name("goods")->where('id', $goods_welfare['goods_id'])->update(['is_welfare' => 0]);
            }
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        //返回支付单号
        $this->success('OK', $res, 200);
    }
}
